<?php
/*
 *商家订单控制器类
 */
namespace Home\Controller;
use Think\Controller;
class OrderController extends  HomeController {
	public function index()
	{
		//获取所有上架产品
		$shopid=!empty($_SESSION['shopid'])?$_SESSION['shopid']:1;
		$arg['page']=I('get.page','1','strip_tags');
		$order=D('order');
		$result=$order->index($arg);

		$this->assign('orders',$result['orders']);
		$this->assign('pagearr',$result['pagearr']);
		$this->display('index');	
	}
	/*
	 * 查看订单详情
	 * @param shopid 商家id
	 * @param orderid 订单id
	 */
	public function getOrder()
	{
		$shopid=!empty($_SESSION['shopid'])?$_SESSION['shopid']:'188';
		$orderid=I('get.orderid','','strip_tags');
		$order=M('order a ');
		$orderdetail=$order->join('inner join '.C('DB_PREFIX').'order_item b on a.orderid=b.orderid')
		                   ->where('a.shopid=%d AND b.orderid=%d',$shopid,$orderid)
					       ->getField('a.orderid,a.order_sn,a.shopid,a.mobile,a.create_time,a.pay_time,a.address,a.province,a.city,a.district,a.order_amount,a.consignee,a.deviceid,b.supperid,a.settlestatus,a.pay_type,a.shipping_status,a.pay_status,
					       	a.order_status,b.number,b.price,b.productid,b.itemname,b.specvale,b.supperprice');
	    //计算订单状态
		$orderstatus=$orderdetail[$orderid]['order_status']+$orderdetail[$orderid]['pay_status']+$orderdetail[$orderid]['shipping_status'];

	    //获取经销商信息
	    $shopinfo=M('shop_user')->where('shopid=%d',$shopid)->getField('shopid,companyname,address,mobile,telephone');
	    //获取此订单供应商信息
	    $supperid=!empty($orderdetail[$orderid]['supperid'])?$orderdetail[$orderid]['supperid']:'';
	    $supperinfo=M('supper_user')->where('supperid=%d',$supperid)->getField('supperid,name,mobile,telephone,address,companyname,contactname');
	   ///获取毛利毛利率
	    $map['itemid']=M('order_item')->where("orderid='%d'",$orderid)->getField("itemid");
		$over=M('item')->where($map)->Field("price,supperprice")->find();
		$profit=$over['price']-$over['supperprice'];///毛利额
		$rate=$profit/$over['price'];///毛利率
		$rate=round($rate,2);
		$rate=$rate*100;

		$this->assign('profit',$profit)->assign("rate",$rate);


	    $this->assign('shopinfo',$shopinfo[$shopid]);
	    $this->assign('supperinfo',$supperinfo[$supperid]);
	    $this->assign('order',$orderdetail[$orderid]);
	    $this->assign('orderstatus',$orderstatus);
	    $this->display('orderdetail');

	}
	/*
	 * 商家支付订单接口
	 * @param orderid
	 * 
	 * 
	 */
	public function payOrder(){
		$orderid=I('post.orderid','','strip_tags');
		$order_amount=I('post.order_amount','','strip_tags');
		$order_amount=intval($order_amount);
		$shopid=!empty($_SESSION['shopid'])?$_SESSION['shopid']:'';
		//检测金额，库存
		$order=M('order');
		$order_item=M('order_item');
		$item=M('item');
		$ad_amount=$order->where('orderid=%d',$orderid)->getField('order_amount');
		$order_sn=$order->where('orderid=%d',$orderid)->getField('order_sn');
		if ($ad_amount !=$order_amount)
		{
			$result["status"]=0;
			$result["msg"]='金额不正确';
			echo json_encode($result,JSON_UNESCAPED_UNICODE);
			return '';
		}
		$res=$order_item->where('orderid=%d',$orderid)->getField('productid,number'); //订单商品数量
		$productid=array_keys($res)[0];
		$number=intval(array_values($res)[0]);		
		$inventory=M('product')->where('productid=%d',$productid)->getField('inventory');
		//检测库存
		if ($number >$inventory) {
			$result["status"]=0;
			$result["msg"]='库存不足';
			echo json_encode($result,JSON_UNESCAPED_UNICODE);
			return '';
		}
		//检测加盟商家余额 
		$shop_user=M('shop_user');
		$money=M('shop_user')->where('shopid=%d',$shopid)->getField('money');
		$money=intval($money);
		if ($money<$order_amount) 
		{
			$result["status"]=0;
			$result["msg"]='钱包金额不足，请充值';
			echo json_encode($result,JSON_UNESCAPED_UNICODE);
			return '';
		}
		//支付
		
		$shop_user=M('shop_user');
		$account_log=M('account_log');
		$order=M('order');
		$order_action=M('order_action');
		$shop_user->startTrans();
		$temp=$shop_user->where('shopid=%d',$shopid)->setDec('money',$order_amount);
		if ($temp !== false) {
			//修改订单状态
			$map=array('order_status'=>1,'shipping_status'=>0,'pay_status'=>2);
			$upstatus=$order->where('orderid=%d',$orderid)->setField($map);
		}
		//更新支付记录
		$data['change_time']=time();
		$data['change_desc']="支付订单$order_sn ;金额：$ad_amount";
		$data['change_type']=99;// 其他类型
		$data['shop_money']=-$ad_amount;
		$data['shopid']=$shopid;
		$logid=$account_log->add($data);
		//添加order_action 表，订单操作记录
	    	$map['edittime']=time();
	    	$map['order_id']=$orderid;
	    	$map['action_user']=$_SESSION['username'];
	    	$add_action=$order_action->add($map);

	    

		

		if ($temp !== false && !empty($logid) && $upstatus !== false && $add_action !== false ) {
			$shop_user->commit();
			$result["status"]=1;
			$result["msg"]='订单支付成功';
			echo json_encode($result,JSON_UNESCAPED_UNICODE);
			return '';
		}else{
			$shop_user->rollback();
			$result["status"]=0;
			$result["msg"]='网络连接错误';
			echo json_encode($result,JSON_UNESCAPED_UNICODE);
			return '';
		}
	}
	/*
	 ×取消订单
	 ×@param orderid 
	 *rturn json
	 *
	 */
	public function cancelOrder(){

		$orderid=I('post.orderid',0,'strip_tags');
		$result=array();
		if (empty($orderid))
		{
			$result['status']=0;
			$result['msg']='系统繁忙请稍后在试';
			echo json_encode($result);
			return '';
		}
		//判断此订单状态（只有已确认订单和未确认订单可以取消）
		$order=M('order');
		$orderstatus=$order->where('orderid=%d',$orderid)->getField('order_status+shipping_status+pay_status as orderstatus');
		$orderstatus=intval($orderstatus);
		if($orderstatus >1)
		{
			$result['status']=0;
			$result['msg']='订单配货中，请联系客服取消订单';
			echo json_encode($result);
			return '';
		}
		//更改订单状态
		$order->create();
		$order->order_status=2;
		$order->shipping_status=0;
		$order->pay_status=0;
		$temp=$order->where('orderid=%d',$orderid)->save();
		//写入订单操作记录
		if(!empty($temp))
		{
			$order_action=M('order_action');
			$order_action->create();
			$order_action->order_id=$orderid;
			$order_action->action_user=!empty($_SESSION['username'])?$_SESSION['username']:'';
			$order_action->order_status=2;
			$order_action->shipping_status=0;
			$order_action->pay_status=0;
			$order_action->edittime=time();
			$order_action->add();
			$result['status']=1;
			$result['msg']='订单取消成功';
			echo json_encode($result);
			return '';
		}else{
			$result['status']=0;
			$result['msg']='系统繁忙请稍后在试';
			echo json_encode($result);
			return '';
		}
		

	}
	/*
	 *删除订单
	 *param orderid
	 *return json
	 */
	public function delOrder()
	{
		$orderid=I('get.orderid',0,'strip_tags');
		$orderid=intval($orderid);
		$where['orderid']=$orderid;
		//获取订单状态

		$temp=M()->query('select (order_status+pay_status+shipping_status) as status from '.C(DB_PREFIX).'order where orderid='.$orderid);
		$status=$temp[0]['status'];
		$status=intval($status);
		$order=M('order');
		$order_item=M('order_item');
		
		 //订单已取消
		$result=array();

		if ($status ===2 || $status===0)
		{
			

			//$order=$order->startTrans(); 事务支持有问题

			$result1=$order->where($where)->delete();
			$result2=$order_item->where($where)->delete();
			if ($result1 && $result2)
		    {
				//$order->commit();//删除成功
			    $result['status']=1;
			    $result['msg']='删除成功';
			    echo json_encode($result,JSON_UNESCAPED_UNICODE);
			    return '';
			}else{
				//$order->rollback();
				$result['status']=0;
			    $result['msg']='系统繁忙';
			    echo json_encode($result,JSON_UNESCAPED_UNICODE);
			    return '';
			}
		}
		$result['status']=0;
		$result['msg']='请先取消订单在删除';
		echo json_encode($result,JSON_UNESCAPED_UNICODE);
		return '';

	}
	//ajax 调用订单操作记录
	public function orderAction()
	{
		$result=array();
		$orderid=I('post.orderid',0,'strip_tags');
		$action=D('Order');

		$temp=$action->orderLog($orderid);
		
		if(!empty($temp)) {
			$result['status']=1;
			$result['logs']=array_values($temp);
			echo json_encode($result,JSON_UNESCAPED_UNICODE);
		}else{
			$result['status']=0;
			echo json_encode($result,JSON_UNESCAPED_UNICODE);
		}
	}
	/**
	 * 订单搜索
	 */
	public function Ordersearch()
	{
       $arg=array();
       $starttime=I('post.starttime','','strip_tags');
       $arg['starttime']=strtotime($starttime);
       $endtime=I('post.endtime','','strip_tags');
       $arg['endtime']=strtotime($endtime);
       $arg['page']=I('post.page',1,'strip_tags');
       $arg['orderarea']=I('post.orderarea',2,'strip_tags'); //默认网购区
       $order=D('Order');
       $orders=$order->index($arg);
     
       $result=array();
       $result['status']=!empty($orders['orders'])?1:0;
       $result['lists']=$orders;
       echo json_encode($result);
       return ''; 
	}
	/*
	 *@param orderid
	 *return bool
	 */
	public function confirmOrder()
	{
		$result='';
		$orderid=I('post.orderid','','strip_tags');
		$order=M('order');
		//判断订单状态
		$temp=$order->where('orderid=%d',$orderid)->getField('shipping_status+order_status+pay_status as temp' );
		if($temp>0)
		{
			$result['status']=2;
			$result['msg']='此订单已确认';
			echo json_encode($result);
			return '';
		}
		$action=M('order_action');
		$order->startTrans();
		$order->create();
		$order->order_status=1;
		$order->shipping_status=0;
		$order->pay_status=0;
		$temp1=$order->where('orderid=%d',$orderid)->save();
		$action->create();
		$action->order_id=$orderid;
		$action->action_user=$_SESSION['username'];
		$action->order_status=0;
		$action->shipping_status=0;
		$action->pay_status=1;
		$action->edittime=time();
		$temp2=$action->add();
		if($temp1!==false && $temp2)
		{
			$order->commit();
			$result['status']=1;
			$result['msg']='订单确认成功';
			echo json_encode($result);

			return '';
		}else{
			$order->rollback();
			$result['status']=0;
			$result['msg']='系统繁忙请稍后在试';
			echo false;
			return '';
		}

	}
	/*
	 *确认收货
	 *@orderid
	 *return josn
	 */
	public function confirmreceipt()
	{
		$result='';
		$orderid=I('post.orderid','','strip_tags');
		$order=M('order');
		//判断订单状态
		$temp=$order->where('orderid=%d',$orderid)->getField('shipping_status+order_status+pay_status as temp' );
		if($temp==9)
		{
			$result['status']=2;
			$result['msg']='此订单已收货';
			echo json_encode($result);
			return '';
		}
		$action=M('order_action');
		$order->startTrans();
		$order->create();
		$order->order_status=5;
		$order->shipping_status=2;
		$order->pay_status=2;
		$temp1=$order->where('orderid=%d',$orderid)->save();
		$action->create();
		$action->order_id=$orderid;
		$action->action_user=$_SESSION['username'];
		$action->order_status=5;
		$action->shipping_status=2;
		$action->pay_status=2;
		$action->edittime=time();
		$temp2=$action->add();
		if($temp1!==false && $temp2)
		{
			$order->commit();
			$result['status']=1;
			$result['msg']='收货成功';
			echo json_encode($result);

			return '';
		}else{
			$order->rollback();
			$result['status']=0;
			$result['msg']='系统繁忙请稍后在试';
			echo false;
			return '';
		}

	}
}